package org.example;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/orders")
public class OrderServlet extends HttpServlet {
    private OrderDAO orderDAO = new OrderDAO();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        
        List<Order> orders = orderDAO.getAllOrders(); // 获取所有订单
        PrintWriter out = response.getWriter();
        out.print("[");
        for (int i = 0; i < orders.size(); i++) {
            Order order = orders.get(i);
            out.print("{");
            out.print("\"id\":" + order.getId() + ",");
            out.print("\"bookId\":\"" + order.getBookId() + "\",");
            out.print("\"bookName\":\"" + order.getBookName() + "\",");
            out.print("\"bookPrice\":" + order.getBookPrice() + ",");
            out.print("\"buyerName\":\"" + order.getBuyerName() + "\",");
            out.print("\"address\":\"" + order.getAddress() + "\",");
            out.print("\"phone\":\"" + order.getPhone() + "\"");
            out.print("}");
            if (i < orders.size() - 1) {
                out.print(",");
            }
        }
        out.print("]");
        out.flush();
    }

}
